<?php namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Panorama;
use Illuminate\Http\Request;

class ViewController extends Controller {
	public function __construct(){
		$this->middleware('admin', ['except' => ['login', 'logout']]);
	}

	public function getIndex(){
		return view('admin/view');
	}

	public function getPageRows(Request $request){
		$user_id = session('token')['user_id'];
		$limit = to_limit_lng($request->input('limit'),1);
		$page = to_limit_lng($request->input('page'),1);
		$rows = Panorama::where('user_id',$user_id)->paginate($limit);
		return $this->response($rows);
	}

	public function postUploadFile(Request $request) {
		$user_id = session('token')['user_id'];
		if (!$request->hasFile('file')) {
			return $this->error('无效的文件');
		}
		$file = $request->file('file');

		$target_path = 'upload/' . date('Y/m/d/');
		$targetPath = public_path() . '/' . $target_path;
		if (!is_dir($targetPath)) {
			if (!mkdir($targetPath, 0777, 1)) {
				return $this->error('无法建立上传目录');
			}
		}

		$name = $orig_name = safe($request->input('name'));
		$file_type = safe($request->input('type'), 50);
		$file_size = intval($request->input('size'));
		$file_ext = strtolower(get_file_ext($name));

		if (!in_array($file_ext, config('constants.allowExt'))) {
			return $this->error('上传文件的类型不支持');
		}

		$new_filename = uniqid() . '.' . $file_ext;
		$file->move($targetPath, $new_filename);
		$pic = $target_path . $new_filename;

		$data = compact('user_id', 'name', 'pic', 'orig_name', 'file_type', 'file_size', 'file_ext');
		$row = new Panorama;
		foreach ($data as $key => $val) {
			$row->$key = $val;
		}
		if ($row->save()) {
			return $this->response($row);
		}
		return $this->error('文件上传失败');
	}

	//预览
	public function getPreview(Request $request){
		$id = intval($request->input('id'));
		$row = Panorama::find($id);
		if (empty($row)) {
			return $this->error('无效的记录');
		}
		return $this->response($row);	
	}

	//删除
	public function postRemoveFile(Request $request){
		$ids = explode('|', $request->input('ids'));
		if (empty($ids)) {
			return $this->error('无效的参数');
		}

		foreach ($ids as $id) {
			$row = Panorama::find($id);
			if (!empty($row)) {
				$file1 = $row->pic;
				if ($row->delete()) {
					file_exists($file1) && unlink($file1);
				}
			}
		}
		return $this->response($ids);
	}

	//编辑
	public function postRndir(Request $request) {
		$id = intval($request->input('id'));
		$name = $request->input('name');
		$row = Panorama::find($id);
		if (empty($row)) {
			return $this->error('无效的文件');
		}
		$row->name = $name;
		$row->save();
		return $this->response($row);
	}
}